package com.ruiyian.netty.nettyUdpserver;

import com.ruiyian.common.core.redis.RedisCache;
import com.ruiyian.common.utils.spring.SpringUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 报文处理器
 */
@Component
@ChannelHandler.Sharable
public class NettyUdpHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static final Logger LOG = LoggerFactory.getLogger(NettyUdpHandler.class);

    private static AtomicInteger atomicInteger=new AtomicInteger(0);

    private Map<String, String> bridgeDataMap = new HashMap<String, String>();

    // redis缓存依赖
    private static RedisCache redisCache;

    static {
        redisCache = SpringUtils.getBean(RedisCache.class);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket dp) {
        try {
            int length = dp.content().readableBytes();
            //分配一个新的数组来保存具有该长度的字节数据
            byte[] array = new byte[length];
            //将字节复制到该数组
            dp.content().getBytes(dp.content().readerIndex(), array);
            // 新建字符串缓存
            StringBuilder hexStringBufferequipid = new StringBuilder();
            StringBuilder hexStringBuffertemp = new StringBuilder();
            StringBuilder hexStringBufferhumi = new StringBuilder();
            // 循环处理数据
            for (int i=0;i<array.length;i++) {
                // 获取设备id
                if(i>=3&&i<=6){
                    String hexString = String.format("%c", array[i]);
                    hexStringBufferequipid.append(hexString);
                }
                // 获取温度
                else if(i==9){
                    String hexString = String.format("%d", array[i]);
                    hexStringBuffertemp.append(hexString);
                    hexStringBuffertemp.insert(hexString.length()-1, ".");
                }
                // 获取湿度
                else if(i==10){
                    String hexString = String.format("%d", array[i]);
                    hexStringBufferhumi.append(hexString);
                }
            }
            // 时间
            Long timeStamp = System.currentTimeMillis();
            bridgeDataMap.put("timestamp", String.format("%d", timeStamp));
            // 温度
            bridgeDataMap.put("temp", hexStringBuffertemp.toString());
            // 湿度
            bridgeDataMap.put("humi", hexStringBufferhumi.toString());
            // 存到缓存
            redisCache.setCacheObject(hexStringBufferequipid.toString(), bridgeDataMap);
//            System.out.println(String.format("凝冰数据:%s 字节长度：%d", hexStringBufferequipid.toString(),length));
//            LOG.info("收到UDP报文，报文内容:{} 包处理个数:{}", new String(array),atomicInteger.incrementAndGet());
        } catch (Exception e) {
            LOG.error("报文处理失败，失败原因:{}", e.getMessage(), e);
        }
    }
}
